/*
 * lcd.c
 * 
 * Copyright 2012 Kamil Cukrowski <kamil@dyzio.pl>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation version 2.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * 
 */
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#include "lcd.h"

#include <stdio.h>
char *LCD_file;
int LCD_fd;

void LCD_set_file(char *pnt) 
{
	/* keep in mind it does not allocates and copies the name
	* so it needs to be allocated all the time :/ 
	* so it is used with argv[optind] ! */
	LCD_file = pnt;
}

int LCD_rst()
{
	int ret;
	ret = write(LCD_fd, "\033[H\033[J",6);
	if ( ret != 6 )
		return(-1);
	return(0);
}

int LCD_init()
{
	LCD_fd = open(LCD_file, O_WRONLY,0);
	if ( LCD_fd == -1 )
		return(LCD_fd);
	if ( LCD_rst() )
		return -2;
	return(0);
}

int LCD_print(char *text, int size)
{
	if ( write(LCD_fd,text,size) != size ) 
		return(-1);
	return(0);
}

int LCD_print_xy(char col, char row, char *text, int size)
{
	char buff[LCD_buff_size] = { 
		[0] = 0x1B,
		[1] = '[',
		[2] = 'Y',
		[3] = row,
		[4] = col,
	};
	if ( ( LCD_print(buff, 5) != 0 ) || ( LCD_print(text,size) != 0 ) )
		return(-1);
	return(0);
}

int LCD_clr_line(int line)
{
	int i;
	char buff[LCD_COL];
	for (i = 0; i < LCD_COL; i++)
		buff[i]=' ';
	return(LCD_print_xy(0,line,buff,LCD_COL));
}


int LCD_ok(void)
{
	return fcntl(LCD_fd, F_GETFL) != -1 || errno != EBADF;
}

int LCD_fsync()
{
	return fsync(LCD_fd);
}

void LCD_close()
{
	LCD_rst();
	close(LCD_fd);
}
